package service

import (
	"delivery-server/utils/response"
	"github.com/go-xorm/xorm"
)

// CategoryService 菜品种类服务
type CategoryService interface {

	// TryToAddCategory 新增地点事务
	TryToAddCategory(name string) (code int)

	// QueryAllCategories 查询所有菜式
	QueryAllCategories() (results []map[string]string, err error)

	// DeleteCategory 删除菜式
	DeleteCategory(categoryId int) (err error)
}

// NewCategoryService 创建一个菜式服务对象
func NewCategoryService(engine *xorm.Engine) CategoryService {
	return &categoryService{
		Engine: engine,
	}
}

// 菜式服务结构体
type categoryService struct {
	Engine *xorm.Engine
}

// 查询一个菜式名是否已被注册
func (cs categoryService) queryCategoryByName(name string) (exist bool, err error) {
	sqlStr := "SELECT id FROM category WHERE name = ? AND invalidity = 0"
	results, err := cs.Engine.QueryString(sqlStr, name)
	if err != nil {
		panic(err.Error())
	}
	exist = len(results) > 0
	return
}

// 插入一个菜式
func (cs categoryService) insertCategory(name string) (err error) {
	sqlStr := "INSERT INTO category(name) VALUES (?)"
	_, err = cs.Engine.Exec(sqlStr, name)
	if err != nil {
		panic(err.Error())
	}
	return
}

// TryToAddCategory 新增地点事务
func (cs categoryService) TryToAddCategory(name string) (code int) {

	var errCode = response.ServerErrCode

	// 新建事务
	session := cs.Engine.NewSession()
	defer session.Close()

	// 事务开始
	err := session.Begin()
	if err != nil {
		return errCode
	}

	// 查询菜式名是否已占用
	exist, err := cs.queryCategoryByName(name)
	if err != nil {
		return errCode
	}

	if exist {
		err = session.Rollback()
		if err == nil {
			return response.CategoryExistCode
		} else {
			return errCode
		}
	}

	// 插入数据
	err = cs.insertCategory(name)
	if err != nil {
		err = session.Rollback()
		return errCode
	}

	// 提交事务
	err = session.Commit()
	if err != nil {
		return errCode
	}

	return response.SuccessCode
}

// QueryAllCategories 查询所有菜式
func (cs categoryService) QueryAllCategories() (results []map[string]string, err error) {
	sqlStr := "SELECT id, name FROM category WHERE invalidity = 0"
	return cs.Engine.QueryString(sqlStr)
}

// DeleteCategory 删除菜式
func (cs categoryService) DeleteCategory(categoryId int) (err error) {
	sqlStr := "UPDATE category SET invalidity = 1 WHERE id = ?"
	_, err = cs.Engine.Exec(sqlStr, categoryId)
	if err != nil {
		panic(err.Error())
	}
	return
}
